# https://blog.csdn.net/ClushioAqua/article/details/129834114
# 每个视频修改oid
# 两个函数都有file
import requests
from bs4 import BeautifulSoup
import re
import json
from pprint import pprint
import time
 
#网页头
# headers = {
#     "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36",
#     "referer" : "https://www.bilibili.com/"
# }
# 视频oid【从main?csrf》data》replies》oid》获得oid】
# oid=820459086
# file = open(f'C:\\Users\\King\\Desktop\\{oid}.txt', 'w',encoding='utf-8')

# 视频详情
# https://api.bilibili.com/x/web-interface/wbi/view/detail?aid=402585244&need_view=1&web_location=1315873&w_rid=8e18a7f154598a319aec4405036c00eb&wts=1692708283

# f12》网络》fetch/xhr》main?csrf...》【# 标头+预览】【下拉后，main标头不变？？？】
# https://api.bilibili.com/x/v2/reply/main?csrf=ec7f91ac569eb8d93ff30d57c2c0da29&mode=3&oid=402585244&pagination_str={%22offset%22:%22{\%22type\%22:1,\%22direction\%22:1,\%22session_id\%22:\%221733333285100228\%22,\%22data\%22:{}}%22}&plat=1&type=1热门评论
# https://api.bilibili.com/x/v2/reply/main?csrf=ec7f91ac569eb8d93ff30d57c2c0da29&mode=3&oid=402585244&pagination_str={"offset":""}&plat=1&seek_rpid=&type=1
# 预览》data》replies》0-10》content（初up置顶评论）的根目录
# 预览》data》replies》0-10》根目录的子评论replies（0-2）展开之后才有0-10

# f12》网络》fetch/xhr》reply?csrf...》
# https://api.bilibili.com/x/v2/reply/reply?csrf=ec7f91ac569eb8d93ff30d57c2c0da29&oid=402585244&pn=2&ps=10&root=171168386224&type=1
# https://api.bilibili.com/x/v2/reply/reply?csrf=ec7f91ac569eb8d93ff30d57c2c0da29&oid=402585244&pn=1&ps=10&root=171168386224&type=1
# https://api.bilibili.com/x/v2/reply/reply?csrf=ec7f91ac569eb8d93ff30d57c2c0da29&oid=402585244&pn=1&ps=10&root=171709696352&type=1
# 根：root》content（根评论）》oid,type，     子：replies》pn页
# 预览》data》replies》子目录未展开只有0-3，展开后0-9，点击下一页又加载0-9，

def get_SecondReply(root,oid,filepath):
    headers = {
    "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36",
    "referer" : "https://www.bilibili.com/"
    }
    oid=oid
    pn = 1
    file=open(filepath, 'a+',encoding='utf-8')
    while True:
        # pn 页，root来自每个根评论的rpid【获取子评论】
        URL = (f"https://api.bilibili.com/x/v2/reply/reply?jsonp=jsonp&pn={pn}&type=1&oid={oid}&ps=10&root={root}")#模板
# replies?csrf   https://api.bilibili.com/x/v2/reply/reply?                          &oid=470113786&pn=1&ps=10&root=117316316480&type=1
#         URL = (f"https://api.bilibili.com/x/v2/reply/reply?jsonp=jsonp&pn={pn}&type=1&oid=824175427&ps=10&root={root}&_=1679992607971")#root是根评论的root
        respond = requests.get(URL , headers = headers) # 获得源代码 抓包
        reply_num = 0
        if(respond.status_code == 200):
            respond.encoding = "UTF-8"
            html = respond.text
            json_html = json.loads(html)
            
            if json_html['data']['replies'] is None:
                if(pn == 1):
                    return 0
                else :
                    return 1
            
            for i in range(0,len(json_html['data']['replies'])):
                if json_html['data']['replies'] is None:
                    break
                reply = json_html['data']['replies'][reply_num]['content']['message']
                uname=json_html['data']['replies'][reply_num]['member']['uname']#加入用户名
                reply = reply.replace('\n',',')
                print(uname+"》: "+reply)
                reply_num += 1
                file.write("    " +uname+"》: "+reply+ '\n')
            pn += 1
            time.sleep(0.5)
        else:
            print("Sreply error!")
            exit(-1)
 
    
def get_rootReply(oid,filepath):
    headers = {
    "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36",
    "referer" : "https://www.bilibili.com/"
    }
    file=open(filepath, 'w',encoding='utf-8')
    oid=oid
    num = 1
    replay_index = 1
    while True:
#         【获取根评论】
        URL = (f"https://api.bilibili.com/x/v2/reply/main?&jsonp=jsonp&next={num}&mode=3&oid={oid}&plat=1&type=1")#模板
#         URL = (f"https://api.bilibili.com/x/v2/reply/main?&jsonp=jsonp&next={num}&type=1&oid=470113786&mode=3&plat=1&_=1680096302818")   #获得网页源码
        respond = requests.get(URL , headers = headers) # 获得源代码 抓包
        # print(respond.status_code)
        reply_num = 0
        if(respond.status_code == 200): # 如果响应为200就继续，否则退出
            respond.encoding = "UTF-8"
            html = respond.text
            json_html = json.loads(html)    # 把格式转化为json格式 一个是好让pprint打印，一个是好寻找关键代码
            
            if json_html['data']['replies'] is None or len(json_html['data']['replies']) == 0 :
                break
 
            for i in range(0,len(json_html['data']['replies'])):   #一页只能读取20条评论
                reply = json_html['data']['replies'][reply_num]['content']['message']
                uname=json_html['data']['replies'][reply_num]['member']['uname']#加入用户名
                root = json_html['data']['replies'][reply_num]['rpid']# 【根评论的rpid==root，传给子评论】
                reply = reply.replace('\n',',')
                print(uname+"》: "+reply)
                file.write(str(replay_index) + '.' + uname+"》: "+reply + '\n')
                if json_html['data']['replies'][reply_num]['replies'] is not None:
                    if(get_SecondReply(root,oid,filepath) == 0):
                        for i in range(0,len(json_html['data']['replies'][reply_num]['replies'])):
                            reply = json_html['data']['replies'][reply_num]['replies'][i]['content']['message']
                            uname=json_html['data']['replies'][reply_num]['member']['uname']#加入用户名
                            reply = reply.replace('\n',',')
#                             print(uname+"》: "+reply)
                            file.write("    " +uname+"》: "+ reply + '\n')
                reply_num += 1 
                replay_index += 1
            num += 1
            
            time.sleep(0.5)
        else :
            print("respond error!")
            break
    file.close()
 
# if __name__ == '__main__':
#     oid=559877049
#     file = open(f'C:\\Users\\King\\Desktop\\{oid}.txt', 'w',encoding='utf-8')
#     get_rootReply(headers,oid)
#     print("********************成功********************")


# oid=
# filepath="C:\\Users\\King\\Desktop\\1.txt"
# get_rootReply(oid,filepath)